<?php
/**
 * 权限管理之配置权限
 * Date: 2015/6/19
 * Time: 9:10
 */

namespace AdminV3\Controller;
use Think\Controller;

class AccessController extends CommonController
{
    //显示权限
    public function index()
    {
        if(isset($_GET['rid'])){
            //判断是否已经存在了权限并传递已经存在的权限id
            $accessData = M('access')->where('role_id='.I('get.rid'))->field('GROUP_CONCAT(node_id order by node_id) as nodelist')->select();
            $nodeList = $accessData[0]['nodelist'];
            if(!empty($nodeList)) $this->assign('nodeList',$nodeList);

            //当前系统所有开启状态的权限
            $nodeAppData = M('node')->where('status = 1 and level = 1')->order('sort')->select();
                foreach($nodeAppData as $key=>$value){
                    $nodeAppData[$key]['controller'] =  M('node')->where('status = 1 and level = 2 and pid='.$value['id'])->order('sort')->select();
                    foreach($nodeAppData[$key]['controller'] as $k=>$v){
                        $nodeAppData[$key]['controller'][$k]['action'] = M('node')->where('status = 1 and level =3 and pid='.$v['id'])->order('sort')->select();
                    }
                }

            $role= M('role')->where('id='.I('get.rid'))->field('id,name')->select();
            $this->assign('role',$role[0]);

            $this->assign('nodeData',$nodeAppData);
            $this->display();
        }else{
            $this->error('非法操作！');
        }
    }

    //权限添加和修改
    public function addAccess()
    {
        if(isset($_POST['rid']) && isset($_POST['access'])) {
            $access = I('post.access');
            $accessData = array();
            foreach ($access as $k => $v) {
                $data = explode(',', $v);
                $accessData[$k]['role_id'] = I('post.rid');
                $accessData[$k]['node_id'] = $data[0];
                $accessData[$k]['level'] = $data[1];
            }
            $db =M('access');
            $db->startTrans();
            $oldAccessList = $db->where('role_id='.$_POST['rid'])->field('count(node_id) as num')->select();
            $delRe = $db->where('role_id ='.$_POST['rid'])->delete();
            if($delRe == $oldAccessList[0]['num']){
                $re=$db->addAll($accessData);
                if($re){
                    $db->commit();
                    $this->redirect('role/index');
                }else{
                    $db->rollback();
                    $this->error('保存新权限出错！请按正常流程进入该页面。');
                }
            }else{
                $db->rollback();
                $this->error('删除原有权限出错！请按正常流程进入该页面。');
            }
        }else{
            $this->error('非法操作！');
        }

    }
}